package com.liyuxiang.graph.node;

import com.alibaba.cloud.ai.graph.OverAllState;
import com.alibaba.cloud.ai.graph.action.NodeAction;
import com.liyuxiang.graph.service.ConversationHandlingService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class NoIntentQuestionNode implements NodeAction {

    private static final Logger logger = LoggerFactory.getLogger(NoIntentQuestionNode.class);
    private final ConversationHandlingService conversationHandlingService;

    public NoIntentQuestionNode(ConversationHandlingService conversationHandlingService) {
        this.conversationHandlingService = conversationHandlingService;
    }

    @Override
    public Map<String, Object> apply(OverAllState state) throws Exception {
        String query = state.value("query", "");
        String userId = state.value("userId", "unknown");
        List<String> history = state.value("conversationHistory", List.of());

        logger.info("开始AI无意图对话处理 - 用户ID: {}, 输入: {}, 对话轮次: {}", userId, query, history.size());

        try {
            // 使用AI对话处理服务
            ConversationHandlingService.ConversationHandlingResult handlingResult = 
                    conversationHandlingService.handleConversation(query, history, userId);

            // 更新对话历史（避免重复添加用户输入）
            List<String> updatedHistory = new java.util.ArrayList<>(history);
            
            // 检查是否已经包含当前用户输入
            String currentUserInput = "用户: " + query;
            if (!updatedHistory.contains(currentUserInput)) {
                updatedHistory.add(currentUserInput);
                logger.info("添加用户输入到对话历史: {}", currentUserInput);
            } else {
                logger.info("用户输入已存在，跳过重复添加");
            }
            
            String assistantResponse = "助手: " + handlingResult.getResponse();
            updatedHistory.add(assistantResponse);
            logger.info("添加助手回复到对话历史: {}", assistantResponse);

            // 记录详细的对话处理信息
            logger.info("AI对话处理结果 - 用户ID: {}, 对话类型: {}, 引导程度: {}, 语调: {}", 
                    userId, handlingResult.getConversationType(), handlingResult.getGuidanceLevel(), handlingResult.getTone());
            logger.info("参与策略: {}", handlingResult.getEngagementStrategy());
            logger.info("下一步建议: {}", handlingResult.getNextActionSuggestion());

            Map<String, Object> result = new HashMap<>();
            result.put("response", handlingResult.getResponse());
            result.put("nextAction", handlingResult.getNextActionSuggestion());
            result.put("intentType", "无意图");
            result.put("conversationType", handlingResult.getConversationType());
            result.put("guidanceLevel", handlingResult.getGuidanceLevel());
            result.put("tone", handlingResult.getTone());
            result.put("engagementStrategy", handlingResult.getEngagementStrategy());
            result.put("fullAiAnalysis", handlingResult.isFullAiAnalysis());
            result.put("conversationHistory", updatedHistory);
            result.put("isCompleted", true);

            logger.info("AI无意图对话处理完成 - 用户ID: {}, 对话类型: {}, AI分析: {}", 
                    userId, handlingResult.getConversationType(), handlingResult.isFullAiAnalysis());

            return result;

        } catch (Exception e) {
            logger.error("AI无意图对话处理失败 - 用户ID: {}, 错误: {}", userId, e.getMessage(), e);

            // 构建对话历史（备用逻辑）
            List<String> updatedHistory = new java.util.ArrayList<>(history);
            String currentUserInput = "用户: " + query;
            if (!updatedHistory.contains(currentUserInput)) {
                updatedHistory.add(currentUserInput);
            }
            
            // 提供默认的友好回复
            String defaultResponse = getFallbackResponse(query);
            updatedHistory.add("助手: " + defaultResponse);

            Map<String, Object> result = new HashMap<>();
            result.put("response", defaultResponse);
            result.put("nextAction", "引导提问");
            result.put("intentType", "无意图");
            result.put("conversationType", "其他");
            result.put("error", e.getMessage());
            result.put("fallback", true);
            result.put("conversationHistory", updatedHistory);
            result.put("isCompleted", true);
            
            logger.warn("使用默认无意图回复策略");
            return result;
        }
    }

    private String getFallbackResponse(String query) {
        String lowerQuery = query.toLowerCase();
        
        if (lowerQuery.contains("你好") || lowerQuery.contains("hello") || lowerQuery.contains("hi")) {
            return "您好！我是智能问诊助手，可以帮助您分析症状并推荐合适的科室。请告诉我您目前有什么身体不适的地方？";
        } else if (lowerQuery.contains("功能") || lowerQuery.contains("能做什么") || lowerQuery.contains("怎么用")) {
            return "我可以帮您进行智能问诊，通过了解您的症状来推荐最合适的科室。请详细描述一下您的身体状况或不适症状。";
        } else if (lowerQuery.contains("测试") || lowerQuery.contains("试试")) {
            return "欢迎测试我的问诊功能！我可以根据您的症状描述来推荐科室。请告诉我您有什么身体不适吗？比如头痛、发热、腹痛等。";
        } else {
            return "我是您的健康助手，专门帮助分析症状和推荐科室。请告诉我您目前有什么健康方面的问题或身体不适吗？比如头痛、发热、腹痛等症状。";
        }
    }
}